<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>用户登录</h2>
      </div>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
        label-width="80px"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
            clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <div class="captcha-container">
            <el-input
              v-model="loginForm.code"
              placeholder="请输入验证码"
              prefix-icon="Key"
              clearable
              style="width: 60%"
            />
            <div class="captcha-image" @click="refreshCaptcha">
              <img
                v-if="login.code"
                :src="login.code"
                alt="验证码"
                style="width: 100%; height: 100%; object-fit: cover"
              />
              <div v-else class="captcha-placeholder">点击获取验证码</div>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useLogin } from "../../stores/login";
import { ElMessage } from "element-plus";
import { login as loginApi } from "../../api/consumer/login";
import { useRouter } from "vue-router";
import { LoginParams } from "../../types/login";
//编程式导航
const router = useRouter();
const login = useLogin();
const loginFormRef = ref();
//用于追踪是否刷新
const loading = ref(false);
const codeKey = ref<string>("");
// 登录表单数据输入文本
const loginForm = reactive<LoginParams>({
  phone: "18345678910",
  key: codeKey.value,
  code: "",
  password: "12345678910",
});

// 表单验证规则
const loginRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { min: 4, max: 4, message: "验证码为4位", trigger: "blur" },
  ],
};
// 刷新验证码
const refreshCaptcha = async () => {
  try {
    await login.getCode();
    codeKey.value = login.key;
    // ElMessage.success("验证码已刷新");
  } catch (error) {
    ElMessage.error("获取验证码失败");
  }
};

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();
    loading.value = true;

    // 手动同步key，防止刷新后key丢失
    loginForm.key = codeKey.value;

    const result = await loginApi(loginForm);
    console.log(result);
    //原来
    localStorage.setItem("token", result.data.token);
    if (result.code === 1) {
      // 登录成功后跳转
      setTimeout(() => {
        ElMessage.success("登录成功");
        loading.value = false;
        // 跳转到首页或其他页面
        router.push("/layout");
      }, 300);
    } else {
      loading.value = false;
      ElMessage.error("登录失败");
    }
    console.log(result);
  } catch (error) {
    loading.value = false;
    ElMessage.error("请检查输入信息");
  }
};

// 测试API连接
// const testApiConnection = async () => {
//   try {
//     ElMessage.info("正在测试API连接...");
//     const result = await login.getCode();
//     console.log("API测试结果:", result);
//     ElMessage.success("API连接成功！");
//   } catch (error) {
//     console.error("API测试失败:", error);
//     ElMessage.error("API连接失败，请检查网络或后端服务");
//   }
// };

// 页面加载时获取验证码
onMounted(() => {
  refreshCaptcha();
});
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin: 0;
  font-size: 24px;
}

.login-form {
  width: 100%;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: #409eff;
}

.captcha-placeholder {
  color: #909399;
  font-size: 12px;
}
</style> 